#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <unistd.h>

#define SIZE 1024

void Usage(const std::string &proc)
{
    std::cout << "\n\rUsage:" << proc << " serviceip port[1024]+\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    struct sockaddr_in service;
    socklen_t len = sizeof(service);
    memset(&service, 0, sizeof(service));
    service.sin_family = AF_INET;
    service.sin_port = htons(port);
    inet_pton(AF_INET, ip.c_str(), &service.sin_addr);
    while (true)
    {
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "sock create error" << std::endl;
            exit(2);
        }
        int cnt = 5;
        bool isreconnect = false;

        do
        {

            // 客户端不需要绑定，不同app之间没有沟通，绑定会出错，操作系统来绑定最好
            int n = connect(sockfd, (struct sockaddr *)&service, len);
            if (n < 0)
            {
                std::cerr << "connect error..., reconnect: " << cnt << std::endl;
                cnt--;
                isreconnect = true;
                sleep(2);
            }
            else
            {
                isreconnect = false;
            }
            
        } while (cnt && isreconnect);

        if(cnt == 0)
        {
            std::cerr << "user offline..." << std::endl;
            close(sockfd);
            break;
        }

            // 开始通信
        std::string message;

        std::cout << "Please enter# ";
        std::getline(std::cin, message);
        ssize_t n = write(sockfd, message.c_str(), sizeof(message));
        if (n < 0)
        {
            std::cerr << "write error" << std::endl;
            continue;
        }
        char inbuffer[SIZE];
        n = read(sockfd, inbuffer, SIZE - 1);
        if (n > 0)
        {
            inbuffer[n] = 0;
            std::cout << inbuffer << std::endl;
            std::cout << "\n";
        }
        close(sockfd);
    }

    return 0;
}